/**
 * @Title: ProductSaleServiceImpl.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 张鑫
 * @phone 17561783855
 * @date 2019年5月22日
 */
package com.fortune.rainshineservice.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.base.ParmsModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.*;
import com.fortune.rainshinecommon.model.service.OrderDetailModel;
import com.fortune.rainshinecommon.model.service.StockModel;
import com.fortune.rainshinecommon.model.service.StockRecordsModel;
import com.fortune.rainshinecommon.query.GetDetailQuery;
import com.fortune.rainshineservice.mapper.*;
import com.fortune.rainshineservice.service.ProductSaleService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author 张鑫
 * @ClassName: ProductSaleServiceImpl
 * @Description: TODO(店铺产品处理 - - 产品销售以及产品领用)
 * @phone 17561783855
 * @date 2019年5月22日
 */
@Service
public class ProductSaleServiceImpl implements ProductSaleService {
    private static final Logger logger = LoggerFactory.getLogger(ProductSaleServiceImpl.class);
    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private StockRecordsMapper stockRecordsMapper;

    @Autowired
    private SaleMapper saleMapper;

    @Autowired
    private SaleDetailMapper saleDetailMapper;

    @Autowired
    private ConsumeRecordMapper consumeRecordMapper;

    @Autowired
    private ConsumeDetailMapper consumeDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    @Transactional
    public MsgModel saleOrUse(StockRecordsModel model) {
        try {
            if (model.getType() == null || (model.getType() != 3 && model.getType() != 4)) {
                return new MsgModel("请求异常，操作类型未知！", ResultCode.FAILURE);
            }
            if (model.getOrderDetail() == null || model.getOrderDetail().isEmpty()) {
                return new MsgModel("请选择产品！", ResultCode.FAILURE);
            }
            if(model.getShopId() == null){
                return new MsgModel("商铺信息异常！", ResultCode.FAILURE);
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String successMsg = "";
            // 判断是否存在操作数据
            BigDecimal orderTotal = BigDecimal.ZERO;
            for (OrderDetailModel item : model.getOrderDetail()) {
                // 根据库存id获取库存信息
                StockModel shopStock = stockMapper.selectByProductAndShop(item.getProductId(), model.getShopId());
                if (shopStock == null) {
                    return new MsgModel("操作失败，未查询到库存信息。", ResultCode.FAILURE);
                }

                // 判断库存数量是否多余购买记录
                boolean f = item.getQuantity() > shopStock.getProductAmount();
                if (f) {
                    return new MsgModel("操作失败，库存数量不够，请及时补货。", ResultCode.FAILURE);
                }
                // 低于库存预警数量，发站内信预警
                if ((shopStock.getProductAmount() - item.getQuantity()) < shopStock.getWarningNum()) {
                    // todo
                }

                model.setCode(uuid);

                // 顾客购买记录
                if (model.getType() == 3) {
                    if(model.getCustomerId() == null){
                        return new MsgModel("顾客参数异常！", ResultCode.FAILURE);
                    }
                    CustomerModel customerModel = customerMapper.selectById(model.getCustomerId());
                    if(customerModel == null){
                        return new MsgModel("顾客信息异常！", ResultCode.FAILURE);
                    }
                    if(customerModel.getCustomerStatus().intValue() != 1){
                        return new MsgModel( "此顾客账号已停用！", ResultCode.FAILURE);
                    }

                    SaleDetailModel saleDetailModel = new SaleDetailModel();
                    saleDetailModel.setSaleCode(uuid);
                    saleDetailModel.setProductId(item.getProductId());
                    ProductModel productModel = productMapper.selectById(item.getProductId());
                    saleDetailModel.setProductPrice(productModel.getShopPrice());
                    BigDecimal totolPrice = productModel.getShopPrice().multiply(new BigDecimal(item.getQuantity()));
                    saleDetailModel.setTotalPrice(totolPrice);
                    saleDetailModel.setQuantity(item.getQuantity());
                    saleDetailModel.setCreateId(model.getUserId());
                    saleDetailModel.setUpdateId(model.getUserId());
                    saleDetailModel.setCreateTime(new Date());
                    saleDetailModel.setUpdateTime(new Date());
                    saleDetailMapper.insert(saleDetailModel);
                    orderTotal = orderTotal.add(totolPrice);
                } else if (model.getType() == 4) {// 门店领用
                    ConsumeDetailModel consumeDetailModel = new ConsumeDetailModel();
                    consumeDetailModel.setConsumeCode(uuid);
                    consumeDetailModel.setProductId(item.getProductId());
                    consumeDetailModel.setQuantity(item.getQuantity());
                    consumeDetailModel.setCreateId(model.getUserId());
                    consumeDetailModel.setUpdateId(model.getUserId());
                    consumeDetailModel.setCreateTime(new Date());
                    consumeDetailModel.setUpdateTime(new Date());
                    consumeDetailMapper.insert(consumeDetailModel);
                }

                // 跟新产品库存信息
                shopStock.setProductAmount(shopStock.getProductAmount() - item.getQuantity());
                shopStock.setUpdateId(model.getUserId());
                shopStock.setUpdateTime(new Date());
                stockMapper.updateById(shopStock);
                // 插入库存记录
                model.setProductId(shopStock.getProductId());
                model.setStockId(shopStock.getId());
                model.setAmount(item.getQuantity());
                model.setCreateId(model.getUserId());
                model.setUpdateId(model.getUserId());
                stockRecordsMapper.insert(model);
            }

            // 顾客购买记录
            if (model.getType() == 3) {
                SaleRecordModel saleRecordModel = new SaleRecordModel();
                saleRecordModel.setCustomerId(model.getCustomerId());
                saleRecordModel.setSaleCode(uuid);
                saleRecordModel.setSalerId(model.getUserId());
                saleRecordModel.setShopId(model.getShopId());
                saleRecordModel.setTotalPrice(orderTotal);
                saleRecordModel.setCreateId(model.getUserId());
                saleRecordModel.setUpdateId(model.getUserId());
                saleRecordModel.setCreateTime(new Date());
                saleRecordModel.setUpdateTime(new Date());
                saleMapper.insert(saleRecordModel);
                successMsg = "购买成功";
            }
            // 门店领用
            if (model.getType() == 4) {
                ConsumeRecordModel consumeRecordModel = new ConsumeRecordModel();
                consumeRecordModel.setConsumeCode(uuid);
                consumeRecordModel.setShopId(model.getShopId());
                consumeRecordModel.setUserId(model.getUserId());
                consumeRecordModel.setCreateId(model.getUserId());
                consumeRecordModel.setCreateTime(new Date());
                consumeRecordModel.setUpdateId(model.getUserId());
                consumeRecordModel.setUpdateTime(new Date());
                consumeRecordMapper.insert(consumeRecordModel);
                successMsg = "领用成功";
            }

            return new MsgModel(successMsg, ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error("saleOrUse =====> {}", e);
            return new MsgModel("操作失败，系统错误", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel list(ParmsModel parm) {
        try {
            Page<StockRecordsModel> page = new Page<>(parm.getPage(), parm.getLimit());
            List<StockRecordsModel> list = new ArrayList<StockRecordsModel>();
            int total = 0;
            if(parm.getType() == 3) {
            	list = stockRecordsMapper.getAllRecords(parm, page);
            	total = stockRecordsMapper.getAllRecordsCount(parm);
            }else if(parm.getType() == 4) {
            	list = stockRecordsMapper.getAllRecordsUse(parm, page);
            	total = stockRecordsMapper.getAllRecordsCountUse(parm);
            }
            page.setRecords(list);
            return new MsgModel(total, page.getRecords());
        } catch (Exception e) {
            logger.error(e.toString());
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel consumeDetails(GetDetailQuery query) {
        try {
            Wrapper<ConsumeDetailModel> wrapper = new EntityWrapper<>();
            wrapper.eq("consume_code", query.getCode());
            Page<ConsumeDetailModel> page = new Page<>(query.getPage(), query.getLimit());
            List<ConsumeDetailModel> list = Optional.ofNullable(consumeDetailMapper.selectPage(page, wrapper)).orElse(Lists.newArrayList());
            if (!list.isEmpty()) {
                list.forEach(e -> e.setProductName(productMapper.getNameById(e.getProductId())));
            }
            return new MsgModel(list.size(), list);
        } catch (Exception e) {
            logger.error("consumeDetails ====> {}", e);
            return new MsgModel("获取领用详情异常", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel saleDetails(GetDetailQuery query) {
        try {
            Wrapper<SaleDetailModel> wrapper = new EntityWrapper<>();
            wrapper.eq("sale_code", query.getCode());
            Page<SaleDetailModel> page = new Page<>(query.getPage(), query.getLimit());
            List<SaleDetailModel> list = Optional.ofNullable(saleDetailMapper.selectPage(page, wrapper)).orElse(Lists.newArrayList());
            if (!list.isEmpty()) {
                list.forEach(e -> e.setProductName(productMapper.getNameById(e.getProductId())));
            }
            return new MsgModel(list.size(), list);
        } catch (Exception e) {
            logger.error("saleDetails ====> {}", e);
            return new MsgModel("获取销售详情异常", ResultCode.FAILURE);
        }
    }
}
